package com.ihighest.app.infox.adapter;

import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.view.ViewGroup;

@SuppressLint("Recycle")
public class NewsFragmentPagerAdapter extends FragmentStatePagerAdapter {
	private ArrayList<Fragment> fragments;
	private FragmentManager fm;
	private Context context;

	public NewsFragmentPagerAdapter(FragmentManager fm) {
		super(fm);
		this.fm = fm;

	}

	public NewsFragmentPagerAdapter(FragmentManager fm, ArrayList<Fragment> fragments) {
		super(fm);
		this.fm = fm;
		this.fragments = fragments;
		// setFragments(fragments);
	}

	@Override
	public int getCount() {
		return fragments.size();
	}

	@Override
	public Fragment getItem(int position) {

		return fragments.get(position);
	}

	@Override
	public int getItemPosition(Object object) {
		return POSITION_NONE;
	}

	public void setFragments(ArrayList<Fragment> mFragments) {
		if (this.fragments != null) {
			FragmentTransaction ft = fm.beginTransaction();

			for (Fragment f : this.fragments) {
				ft.remove(f);
			}

			// ft.commitAllowingStateLoss();
			ft = null;
			fm.executePendingTransactions();
		}
		this.fragments = mFragments;
		notifyDataSetChanged();
	}
	//
	// @Override
	// public Object instantiateItem(ViewGroup container, final int position) {
	// // 得到缓存的fragment
	// Fragment fragment = (Fragment) super.instantiateItem(container,
	// position);
	// // 得到tag，这点很重要
	// String fragmentTag = fragment.getTag();
	//
	// // 如果这个fragment需要更新
	//
	// FragmentTransaction ft = fm.beginTransaction();
	// // 移除旧的fragment
	// ft.remove(fragment);
	// // 换成新的fragment
	// fragment = fragments.get(position % fragments.size());
	// // 添加新fragment时必须用前面获得的tag，这点很重要
	// ft.add(container.getId(), fragment, fragmentTag);
	// ft.attach(fragment);
	// ft.commit();
	//
	// // 复位更新标志
	// // fragmentsUpdateFlag[position % fragmentsUpdateFlag.length] = false;
	//
	// return fragment;
	// }
}
